<?php
class Core_Core_Sessions {
	
	private $session_driver;
	public $error_message;
	public $user_info = array();
	private $user_logged_in;
	private $user_name;
	
	public function __construct(){
		try {
			if(class_exists('Core_Driver_Session')){
				$this->session_driver = new Core_Driver_Session;
				session_cache_expire(60 * 15);
				session_regenerate_id();
			}
			else {
				throw new Exception("Klasa Core_Driver_Session nie istnieje!");
			}
		}
		catch(Exception $error_message){
			return $this->error_message->getMessage();
		}
	}
	
	public function get_user_info_where_user_is_logged_in($name){
		try {
			$this->user_info = $this->get_user_data($name);
			if($this->user_info != null){
				$_SESSION['access_level'] = $this->user_info['access_level'];
				$this->user_info['user_logged_in'] = $this->user_logged_in;
				return $this->user_info;
			}
			else {
				throw new Exception("Nie udało się odebrać danych od użytkownika!");
			}
		}
		catch(Exception $error_message){
			return $error_message->getMessage();
		}
	}
	
	public function is_logged_in(){
		try {
			if(isset($_SESSION['username']) && ($_SESSION['username'] != 'GUEST')){
				$this->user_info = $this->get_user_info_where_user_is_logged_n($_SESSION['username']);
				$this->user_info['user_logged_in'] = TRUE;
				if($this->user_info == null){
					throw new Exception("Tablica user_info jest pusta!");
				}
			}
			else {
				$this->user_info = $this->clear_user_data();
			}
			return $this->user_info;
		}
		catch(Exception $error_message){
			return $error_message->getMessage();
		}
	}
	
	public function login($user_name, $user_password){
		if($this->session_driver->check_user() === TRUE){
			$this->user_info = $this->get_user_info_where_user_is_logged_in($name);
			$_SESSION['user_name'] = $this->user_info['user_name'];
		}
		else {
			$_SESSION['user_name'] = 'GUEST';
			$this->user_info = $this->clear_user_data();
		}
	}
	
	public function logout($user_info_array = array()){
		try {
			if(session_destroy()){
				$_SESSION['user_name'] = "GUEST";
				unset($user_info_array);
				$this->user_info = $this->clear_user_data();
				return $this->user_info;
			}
			else {
				throw new Exception("Nie można zniszczyć sesji ani zapoczątkować nowego stanu aplikacji!");
			}
		}
		catch(Exception $error_message){
			
		}
	}
	
	public function clear_user_data($user_info){
		try {
			$this->user_logged_in = FALSE;
			$this->user_info['access_level'] = 0;
			$_SESSION['user_name'] = "GUEST";
			$_SESSION['access_level'] = $this->user_info['access_level'];
			$this->userInfo['user_logged_in'] = $this->user_logged_in;
			$this->userInfo['user_name'] = 'GUEST';
			return $this->userInfo;
		}
		catch(Exception $error_message){
			return $error_message->getMessage();
		}
	}
	
}